package io.chain.ko.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import io.chain.ko.security.JWTAuthFilter;
import io.chain.ko.security.JWTAuthProvider;
import io.chain.ko.security.JWTLoginFilter;
import io.chain.ko.security.JWTLogoutHandler;
import io.chain.ko.service.JWTTokenService;
import io.chain.ko.service.UserService;

@EnableWebSecurity
public class SecurityWebConfig extends WebSecurityConfigurerAdapter{
	
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	private UserService userService;
	@Autowired
	private JWTTokenService jwtTokenService;
	@Value("${token.timeout}")
	private Long tokenTimeout;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {		
		auth.authenticationProvider(new JWTAuthProvider(userDetailsService));		
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		AuthenticationManager authenticationManager=authenticationManager();
		http.csrf().disable();
		http.authorizeRequests()
		.antMatchers("/user/**").hasRole("USER")
		//.antMatchers("/user/**").permitAll()
		.antMatchers("/druid/**").permitAll()
		//.antMatchers("/druid/**").denyAll()
		.anyRequest().authenticated();
		http.addFilterAfter(new JWTLoginFilter(authenticationManager,jwtTokenService, userService), UsernamePasswordAuthenticationFilter.class);
		http.addFilterAfter(new JWTAuthFilter(jwtTokenService, userService,tokenTimeout), JWTLoginFilter.class);
		http.logout().logoutUrl("/logout/jwt").addLogoutHandler(new JWTLogoutHandler(jwtTokenService, userService,tokenTimeout));
	}
	
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/v2/api-docs",
        "/swagger-resources/configuration/ui",
        "/swagger-resources",
        "/swagger-resources/configuration/security",
        "/webjars/**",
        "/swagger-ui.html"
        );
	}

}
